package com.example.myapplication.views;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.R;
import com.example.myapplication.bean.Student;
import com.example.myapplication.database.DBHelper;
import com.example.myapplication.utils.SpUtils;

// 注册页面的 Activity 类
public class zhuceActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText mEtName;
    private EditText mEtCode;
    private EditText mEtClass;
    private EditText mEtUsername;
    private EditText mEtPassword;
    private Button mBtnRegister;
    private SpUtils mSpUtils;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhuce);
        mEtName = findViewById(R.id.student_name);
        mEtClass = findViewById(R.id.class_name);
        mEtCode = findViewById(R.id.student_code);

        mEtUsername = findViewById(R.id.username);
        mEtPassword = findViewById(R.id.password);
        mBtnRegister = findViewById(R.id.register);
        mBtnRegister.setOnClickListener(this);
        mSpUtils = new SpUtils(this);
    }

    @Override
    public void onClick(View v) {
        String name = mEtName.getText().toString();
        String code = mEtCode.getText().toString();
        String username = mEtUsername.getText().toString();
        String password = mEtPassword.getText().toString();
        String className = mEtClass.getText().toString();

        // 如果所有输入都不为空，则进行注册
        if (allInputNotEmpty(name, code, username, password, className)) {
            Student student = new Student();
            student.setStudent_code(code);
            student.setStudent_name(name);
            student.setUsername(username);
            student.setPassword(password);
            student.setClass_name(className);
            // 插入学生信息到数据库，获取插入后的id
            int id = (int) DBHelper.getInstance(this).insertStudent2(student);
            // 记录当前登录账号的id
            mSpUtils.putInt(SpUtils.LOGIN_KEY, id);

            // 跳转到主页面并清除之前所有的页面
            Intent intent = new Intent(zhuceActivity.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else {
            Toast.makeText(this, "输入不能为空", Toast.LENGTH_SHORT).show();
        }
    }

    // 检查所有输入字符串是否都不为空
    private boolean allInputNotEmpty(String... inputStrings) {
        for (int i = 0; i < inputStrings.length; i++) {
            if (TextUtils.isEmpty(inputStrings[i])) {
                return false;  // 如果有一个为空，则返回 false
            }
        }
        return true;  // 否则返回 true
    }

}
